<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :model-value="visible"
      title="采集参数选择"
      style="min-width: 1200px"
      draggable
      @close="closeDialog"
      destroy-on-close
      align-center
      class="maxhDialog"
    >
      <el-row :gutter="10">
        <!-- 用户列表 -->
        <el-col :span="24">
          <!-- <div class="search-container" style="padding: 18px 15px 0"> -->
          <el-form :model="searchParam" :inline="true">
            <el-form-item label="设备">
              <el-select
                v-model="props.equipId"
                placeholder="请选择设备"
                clearable
                disabled
              >
                <el-option
                  v-for="item in equipList"
                  :key="item.id"
                  :label="`${item.equipCode}`"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="参数类别" prop="paramType">
              <el-select
                v-model="searchParam.paramType"
                placeholder="请选择参数类别"
                clearable
                @change="changeScaParamType"
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList('ScaParamType')"
                  :key="item.value"
                  :label="`${item.label}`"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="resetParams"><i-ep-refresh />重置</el-button>
            </el-form-item>
            <!-- <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item> -->
          </el-form>
          <!-- </div> -->

          <el-card
            shadow="never"
            class="table-container card-table-p15 h-[536px]"
          >
            <el-table
              ref="multipleTable"
              v-loading="loading"
              :data="tableData"
              :key="Math.random"
              @select="handleSelectionChange"
              @select-all="handleAllChange"
              class="card-table"
              border
              height="444px"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column
                label="参数名"
                prop="parameterName"
                min-width="120"
                show-overflow-tooltip
                sortable
              />

              <el-table-column
                label="参数描述"
                prop="parameterDesc"
                min-width="120"
                show-overflow-tooltip
              />
              <el-table-column
                label="数据类型"
                prop="parameterType"
                min-width="120"
                align="center"
                show-overflow-tooltip
                sortable
              >
                <template #default="scope">
                  {{ useDictionary("ScaDataType", scope.row.parameterType) }}
                </template>
              </el-table-column>
              <el-table-column
                label="采集方式"
                prop="collectionFrequency"
                min-width="120"
                align="center"
                show-overflow-tooltip
                sortable
              >
                <template #default="scope">
                  {{
                    useDictionary(
                      "ScaCollectFrequency",
                      scope.row.collectionFrequency
                    )
                  }}
                </template>
              </el-table-column>
              <el-table-column
                label="采集频率"
                prop="collectionFrequencyTime"
                min-width="120"
                align="center"
                show-overflow-tooltip
                sortable
              >
                <template #default="scope">
                  <span v-if="scope.row.collectionFrequencyTime">
                    {{ scope.row.collectionFrequencyTime
                    }}{{
                      scope.row.collectionFrequencyUnit === "s"
                        ? "秒"
                        : scope.row.collectionFrequencyUnit === "m"
                        ? "分钟"
                        : ""
                    }}
                  </span>
                  <span v-else></span>
                </template>
              </el-table-column>
              <el-table-column
                label="参数类别"
                prop="paramType"
                min-width="120"
                align="center"
                show-overflow-tooltip
                sortable
              >
                <template #default="scope">
                  {{ useDictionary("ScaParamType", scope.row.paramType) }}
                </template>
              </el-table-column>

              <el-table-column
                label="计量单位"
                prop="measurementUnit"
                min-width="120"
                align="center"
                show-overflow-tooltip
                sortable
              />
              <el-table-column
                label="显示方式"
                prop="showType"
                align="center"
                min-width="120"
                show-overflow-tooltip
                sortable
              >
                <template #default="scope">
                  {{ useDictionary("ScaShowType", scope.row.showType) }}
                </template>
              </el-table-column>
              <el-table-column
                label="序号"
                align="center"
                prop="sort"
                min-width="120"
                show-overflow-tooltip
                sortable
              />
              <el-table-column
                label="地址"
                prop="url"
                min-width="120"
                show-overflow-tooltip
                sortable
              />
              <el-table-column
                label="备注"
                prop="remarks"
                min-width="100"
                show-overflow-tooltip
              />
            </el-table>

            <el-pagination
              small
              background
              :current-page="pageable.pageNum"
              :page-size="pageable.pageSize"
              :page-sizes="[10, 25, 50, 100]"
              :total="pageable.total"
              layout="total, sizes, prev, pager, next, jumper"
              class="mt-[20px]"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-card>
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import { ElTable } from "element-plus";
import dayjs from "dayjs";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
defineOptions({
  name: "EAMINSPECTIONPLANSELECT",
  inheritAttrs: false,
});

interface SelectOption {
  id?: string;
}
const emit = defineEmits(["update:visible", "echo-info"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Array,
    default: () => {
      return [];
    },
  },
  equipId: {
    type: String,
    default: () => {
      return "";
    },
  },
  equipName: {
    type: String,
    default: () => {
      return "";
    },
  },
  equipCode: {
    type: String,
    default: () => {
      return "";
    },
  },
  isMultiple: {
    type: Boolean,
    default: true,
  },
});

const { visible, isMultiple, equipCode } = toRefs(props);

// 组织机构树
const treeLoading = ref(false);
function handleQuery() {
  search();
}
function resetParams() {
  searchParam.value.paramType = "";
  searchParam.value.relationId = props.equipId;
  search();
}

// 深层拷贝
function deepCopy(val: any) {
  return JSON.parse(JSON.stringify(val));
}

// 表格选择
const totalMultipleSelection: any = ref([]);
// 表格触发全选
function handleAllChange(selecteds: any) {
  if (isMultiple.value) {
    const currentSelection = deepCopy(totalMultipleSelection.value);
    const ids = deepCopy(totalMultipleIds.value);
    if (selecteds.length) {
      tableData.value.map((item: SelectOption) => {
        const indexId = ids.indexOf(item.id);
        if (indexId < 0) {
          totalMultipleSelection.value.push(item);
        }
      });
    } else {
      tableData.value.map((item: SelectOption) => {
        const indexId = ids.indexOf(item.id);
        if (indexId > -1) {
          currentSelection.splice(indexId, 1);
          ids.splice(indexId, 1);
        }
      });
      totalMultipleSelection.value = currentSelection;
    }
  } else {
    delAll();
    ElMessage.warning("单选，请重新选择");
  }
}
// 表格触发单个选择
function handleSelectionChange(val: any, row: SelectOption) {
  let addOptions = false;
  val?.map((item: SelectOption) => {
    if (item.id === row.id) {
      addOptions = true;
    }
  });
  if (!addOptions) {
    const index = totalMultipleIds.value.indexOf(row.id);
    totalMultipleSelection.value.splice(index, 1);
  } else {
    if (isMultiple.value) {
      totalMultipleSelection.value.push(row);
    } else {
      delAll();
      multipleTable.value?.toggleRowSelection(row, true);
      totalMultipleSelection.value = [row];
    }
  }
}

// 右侧人员选择操作
const multipleTable = ref(ElTable);
// 全部清除
function delAll() {
  totalMultipleSelection.value = [];
  multipleTable.value.clearSelection();
}
// 单个删除
function delSingle(current: SelectOption, index: number) {
  totalMultipleSelection.value.splice(index, 1);
  tableData.value.map((item: SelectOption) => {
    if (item.id === current.id) {
      multipleTable.value?.toggleRowSelection(item, false);
    }
  });
}

/** 弹窗展开 初始化数据 */
const totalMultipleIds: any = ref([]);
watch(
  () => totalMultipleSelection,
  async (newVal: any) => {
    const ids: any = [];
    newVal.value?.map((item: SelectOption) => ids.push(item.id));
    totalMultipleIds.value = ids;
  },
  { deep: true }
);

// 请求参数
const requestApi = "/iotadmin/scaequipcollectionparam/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({});

// 初始化搜索参数数据
const searchParamInit = {
  paramType: "",
  relationId: "",
};

const changeScaParamType = (e) => {
  if (e) {
    searchParam.value.paramType = e;
  } else {
    searchParam.value.paramType = "";
  }
};

// 数据请求错误后处理
function requestError() {}

// 数据请求错误后处理
function dataCallBack(data: any) {
  setTimeout(() => {
    data.map((item: SelectOption) => {
      if (totalMultipleIds.value.includes(item.id)) {
        multipleTable.value?.toggleRowSelection(item, true);
      }
    });
  }, 0);
  return data;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  loading,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError
);

const workshopIdList: any = ref([]);
const processCodeList: any = ref([]);
async function getWorkshopIdList() {
  const { data } = await request({
    url: `/mdm/mdmworkshop/getList`,
    method: "post",
    data: {},
  });
  workshopIdList.value = data;
}

async function getProcessCodeList() {
  const { data } = await request({
    url: `/mdm/mdmprocess/getList`,
    method: "post",
    data: {},
  });
  processCodeList.value = data;
}

// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/eam/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};

// 目录树
const catalogList: any = ref([]);

// 获取内容树数据
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/equAssetType/getAvailableTree",
    method: "POST",
    data: {},
  }).then((res) => {
    catalogList.value = res.data;
  });
};

// 获取资产品牌数据
const brandList: any = ref([]);
const getBrandList = async () => {
  await request({
    url: "eam/eamassetbrand/getList",
    method: "post",
    data: {},
  }).then((res) => {
    brandList.value = res.data;
  });
};

//产品列表
const productist = ref([]);
const getProductist = async () => {
  const { data } = await request({
    url: "mdm/mdmproductinfo/getList",
    method: "post",
    data: {},
  });
  productist.value = data;
};
onMounted(() => {
  // getTableList();
  getEquipList();
  // getWorkshopIdList();
  // getProcessCodeList();
});

/** 弹窗展开 初始化数据 */
const oldTotalSelection: any = ref([]);
watch(
  () => props.visible,
  async (newVal: boolean) => {
    if (newVal) {
      totalMultipleSelection.value = deepCopy(props.data);
      oldTotalSelection.value = deepCopy(props.data);
      console.log("props.data", props.data);

      searchParam.value.relationId = props.equipId;
      getTableList();
      dataCallBack(tableData.value);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  totalMultipleSelection.value = oldTotalSelection.value;
  searchParam.value.paramType = "";
  dataCallBack(tableData.value);
  emit("update:visible", false);
}

/** 确定提交 */
async function handleSubmit() {
  if (!isMultiple.value && totalMultipleSelection.value.length > 1) {
    ElMessage.error("请选择单个参数");
  } else {
    emit("update:visible", false);
    emit("echo-info", totalMultipleSelection.value);
  }
}

const equipList = ref([]);
const getEquipList = async () => {
  await request({
    url: "iotadmin/scaequipinfo/getList",
    method: "post",
    data: {},
  }).then((res) => {
    equipList.value = res.data;
  });
};

// 组件销毁时调用
onBeforeUnmount(() => {
  emit("update:visible", false);
  closeDialog();
});
</script>

<style lang="scss" scoped>
:deep(.maxhDialog .el-dialog__body) {
  // max-height: calc(70vh);
  overflow-y: auto;
  padding: 20px;
  .mini-search {
    padding: 8px 12px;
  }
  .el-card__body {
    padding: 15px;
  }
}
// :deep(.el-dialog__body) {
//   padding-bottom: 0px !important;
//   padding-top: 15px !important;
// }
.name:hover {
  background-color: rgb(236, 245, 255) !important;
  color: var(--el-menu-active-color) !important;
  border-radius: 6px;
  svg {
    color: var(--el-menu-active-color) !important;
  }
}
.name svg {
  cursor: pointer;
}
:deep(.el-form--inline .el-form-item) {
  margin-right: 10px;
  margin-bottom: 18px;
}
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color))
    inset !important;
}
.el-button svg {
  margin-right: 0;
}
.card-table-p15 {
  :deep(.el-dialog__body) {
    padding: 15px;
  }
  .card-table {
    line-height: normal;
  }
}

:deep(.el-tree) {
  height: 533px;
}
</style>
